-- v0.01
apidir=shell.resolve("api")
tmpdir=shell.resolve("tmp")

-- For editing out of Minecraft I use an editor that needs an extension (.lua) to get syntax highlighting working
-- To save the ballache of copying and renaming it to a non-extensioned file, I just do that here in the script..
fs.delete(tmpdir.."/brum")
fs.delete(tmpdir.."/logger")
fs.copy(apidir.."/brum.lua",tmpdir.."/brum")
fs.copy(apidir.."/logger.lua",tmpdir.."/logger")

os.unloadAPI(tmpdir.."/brum")
os.loadAPI(tmpdir.."/brum")
os.unloadAPI(tmpdir.."/logger")
os.loadAPI(tmpdir.."/logger")

-- Some global flags to control turtle behaviour
local quitflag = false -- Used to break out of the main routine if there is an error
local completed = false -- Used to signal that the turtle has completed what was asked of it

-- How many inventory slots does the turtle have?
invSlots = 16

-- Refuel if turtle's remaining number of moves are lower than...
brum.setRefuelLevel(100)

-- For rednet message broadcasting to base logging console...
consoleID=33 -- Send messages back to console ID 1

local tArgs = { ... }
term.clear()
term.setCursorPos(1,1)
rednet.open("right") -- Open wireless modem on RH side for communication to base console


------------------
-- MAIN ROUTINE --
------------------

logger.setDebug()

local chunkWidth = 8
local chunkHeight = -8
local chunksToMine = 1

if #tArgs > 0 then
  if tArgs[1] == "help" or tArgs[1] == "Help" then
    print("Usage: chunkmine [chunk edge length] [chunk height] [# chunks]")
    print()
    print("For example, 'chunkmine 8 16 1' would mine an 8x8 chunk, 16")
    print("blocks high, in front of the turtle.")
    print()
    print("Defaults : [chunk edge length] 8")
    print("           [chunk height]     -8")
    print("           [# chunks]          1")
    quitflag = true
  elseif #tArgs == 3 then
  	chunkWidth = tonumber(tArgs[1])
  	chunkHeight = tonumber(tArgs[2])
  	chunksToMine = tonumber(tArgs[3])
	elseif #tArgs == 2 then
  	chunkWidth = tonumber(tArgs[1])
  	chunkHeight = tonumber(tArgs[2])
	elseif #tArgs == 1 then
  	chunkWidth = tonumber(tArgs[1])
  end
end

if (not quitflag) then
	local refuelLevel = brum.getRefuelLevel()
	local currentFuel = brum.fuelcheck()
	
	if currentFuel==0 then
		-- We have no fuel in stock
		logger.crit("No initial fuel")
		error("No initial fuel")
	elseif (currentFuel<refuelLevel) then
		logger.crit("Fuel level < "..refuelLevel.." - please provide more")
		error("Low initial fuel - please provide more")
	end
	
	print("Mine "..chunksToMine.." chunk(s), edge length "..chunkWidth)
	if chunkHeight==0 then
		print("Turtle will continue upwards until a level includes no blocks to mine")
	else
		print("Turtle will mine upwards for "..chunkHeight.." blocks")
	end
	
	logger.info("Chunkmine - w="..chunkWidth..", h="..chunkHeight..", #="..chunksToMine)
		
	local x,y,z = 0,0,0
	local metadata = {}
	local result = false
	local reason = ""

	-- Let's see if we're resuming from a saved position (world or chunk reload?)	
	startX, startY, startZ = brum.loadStart()
	if type(startX)~="number" then
		-- This is our first run, we have no start point saved on disk, so the start
		-- co-ordinates are wherever we are right now
		startX=x
		startY=y
		startZ=z
		brum.saveStart(startX, startY, startZ)
		metadata = {["chunkWidth"]=chunkWidth,
								["chunkHeight"]=chunkHeight,
								["chunksToMine"]=chunksToMine
			 		 		 }
		brum.saveTable(metadata,"mineCuboid")
	else
		logger.debug("Loaded start point as "..startX..","..startY..","..startZ)
		metadata = brum.loadTable("mineCuboid")
		if type(metadata)~="table" then
			logger.warn("Start location loaded, but no metadata on file - will use parameters provided")
			metadata = {["chunkWidth"]=chunkWidth,
									["chunkHeight"]=chunkHeight,
									["chunksToMine"]=chunksToMine
			 		 			 }
			brum.saveTable(metadata,"mineCuboid")
		end
	end	

	-- Load savepoint if one exists
	x,y,z=brum.loadCoords()
	if type(x)~="number" and type(y)~="number" and type(z)~="number" then
		logger.info("No saved location")
		x=currentX
		y=currentY
		z=currentZ
	else
		logger.info("Loaded saved position - I am at pos "..x..","..y..","..z)			
		brum.setCurrentPos(x,y,z)
	end
	
	-- Loop on cube
	while (not completed) do
		result,reason,x,y,z = brum.mineCuboid(metadata["chunkWidth"],metadata["chunkHeight"],startX,startY,startZ)
		if (not result) and (tostring(reason)=="fuel" or tostring(reason)=="full") then
			logger.info("Return home, dump load & refuel")
			result, reason = brum.returnXYZ(0,0,0)
		  brum.orientMe(2)
		  brum.dumpLoad()
	  	brum.getFuel()
		  logger.info("Moving back to "..x..","..y..","..z)
		  result, reason = brum.gotoXYZ(x,y,z)
		  if not result then
		  	logger.warn("Cannot return to restart point - aborting")
		  	break
		  end
		elseif result then
		 	completed=true
		end
	end -- while
	
	brum.clearStart()
	brum.returnXYZ(0,0,0)
	brum.clearCoords()
	brum.orientMe(2)
	brum.dumpLoad()
	brum.orientMe(0)
	logger.info("Finished")
		-- Mine this square, keeping track of if we mine any blocks by counting inventory before and after
		
		-- Record continuation point on exit from square
		-- if square complete then exit loop, otherwise refuel/drop inventory
	
	-- Square finished for one reason or another - move up/down on Y axis according to chunkHeight (+ is up, - is down)
	
	-- On completion, delete continuation file if it exists
end